iT邦幫忙

1

[C#] Validparentheses 解法

c#
  • 分享至 

  • xImage
  •  

判斷如下方結果
Example 1:
Input: ()
Output: true

Example 2:
Input: ()[]{}
Output: true

Example 3:
Input: (]
Output: false

Example 4:
Input: ([)]
Output: false

Example 5:
Input: {[]}
Output: true

使用 Stack 解法

static void Main(string[] args)
{
    string a = "()[]";
    Console.WriteLine(ValidParentheses2(a));
}

private static bool ValidParentheses2(string a)
{
    Stack<char> sta = new Stack<char>();
    foreach (var c in a)
    {
        if (c == '(') sta.Push(c);
        else if (c == '[') sta.Push(c);
        else if (c == '{') sta.Push(c);
        else if (c == ')')
        {
            var top = sta.Pop();
            if (top != '(')
            {
                return false;
            }
        }
        else if (c == '}')
        {
            var top = sta.Pop();
            if (top != '{')
            {
                return false;
            }
        }
        else if (c == ']')
        {
            var top = sta.Pop();
            if (top != '[')
            {
                return false;
            }
        }
    }
    return true;
}

暴力解法

static void Main(string[] args)
{
    string a = "()[]";
    Console.WriteLine(ValidParentheses(a));
}

private static bool ValidParentheses(string a)
{
    var temp = a;
    Dictionary<string, string> dic = new Dictionary<string, string>
            {
                { "(", ")" },
                { "[", "]" },
                { "{", "}" }
            };
    for (int i = 0; i < a.Length; i += 2)
    {
        string first = temp.Substring(i, 1);
        string end = temp.Substring(i + 1, 1);

        if (!dic.ContainsKey(first)) return false;
        if (dic[first] != end) return false;
    }
    return true;
}  

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言